import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { Button, Dropdown, Form, Input, Popconfirm, Select, Space, Table } from 'antd';
import './style.less';
import { DownOutlined, EditOutlined } from '@ant-design/icons';

const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  inputType = 'text', // 新增：输入类型，支持 'text' 或 'select'
  selectOptions = [], // 新增：下拉框选项
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);

  useEffect(() => {
    if (editing) {
      inputRef.current?.focus();
    }
  }, [editing]);

  const selectionsMap = useMemo(() => {
    return selectOptions?.reduce((acc, cur) => {
      acc[cur.value] = cur
      return acc
    }, {})
  }, [selectOptions])

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({
        ...record,
        ...values,
      });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  const renderInput = () => {
    if (inputType === 'select') {
      return (
        <Select
          ref={inputRef}
          style={{ width: '100%' }}
          onBlur={save}
          onPressEnter={save}
          options={selectOptions}
          allowClear
          showSearch
          autoFocus
          defaultOpen
          optionRender={item => {
            return <div>{item?.data?.icon} {item?.label}</div>
          }}
        />
      );
    }
    return <Input ref={inputRef} onPressEnter={save} onBlur={save} />;
  };

  const renderUnEditInput = () => {
    if (inputType === 'select') {
      return <div
        className="editable-cell-value-wrap"
        style={{ paddingInlineEnd: 24 }}
        onClick={toggleEdit}
      >
        <div className='editable-cell-value'>
          <Space>
            {selectionsMap?.[record?.[dataIndex]]?.icon}
            {selectionsMap?.[record?.[dataIndex]]?.label ?? children}
          </Space>
        </div>
        <div className='editable-cell-icon'><DownOutlined /></div>
      </div>
    }
    return <div
      className="editable-cell-value-wrap"
      style={{ paddingInlineEnd: 24 }}
      onClick={toggleEdit}
    >
      <div className='editable-cell-value'>{children}</div>
      <div className='editable-cell-icon'><EditOutlined /></div>
    </div>
  }

  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} 为必输项`,
          },
        ]}
      >
        {renderInput()}
      </Form.Item>
    ) : (<>
      {renderUnEditInput()}
    </>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

const EditableTable = ({
  columns = [],
  dataSource = [],
  rowKey,
  selectedRowKeys = [],
  onSelectChange,
  disableSelect = false,
  size = {},
  onChange = (row, index) => { },
  style = {}
}) => {
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange
  };

  const innerColumns = columns?.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record, index) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        inputType: col.inputType, // 传递输入类型
        selectOptions: col.selectOptions, // 传递下拉选项
        handleSave: (row) => onChange(row, index),
      }),
    };
  });

  return (
    <Table
      components={components}
      rowClassName={() => 'editable-row'}
      bordered={false}
      rowKey={rowKey}
      style={style}
      dataSource={dataSource}
      columns={innerColumns}
      rowSelection={disableSelect ? null : rowSelection}
      size='middle'
      className='editable-table'
      scroll={size}
      pagination={false}
    />
  );
};

export default EditableTable;